package com.hyh.user.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyh.user.dao.MenuMapper;
import com.hyh.user.dao.UserMapper;
import com.hyh.user.domain.LoginUser;
import com.hyh.user.domain.User;
import com.hyh.user.util.RedisCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public UserDetails loadUserByUsername(String number) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getNumber, number);
        User user = userMapper.selectOne(qw);
        if(Objects.isNull(user))
            throw new UsernameNotFoundException("用户不存在");
        // 查询权限信息
        List<String> list = menuMapper.selectAuthentication(user.getId());
        // 将权限信息存入redis当中
        stringRedisTemplate.opsForValue().set(RedisCodeUtil.LOGIN_USER_AUTH_KEY+user.getId(),
                Arrays.toString(list.toArray()),
                RedisCodeUtil.LOGIN_USER_KEY_TTL,
                TimeUnit.MINUTES);
        return  new LoginUser(user, list);
    }
}
